﻿using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace AnnieSharp
{
    public class CanvasRender : AObject, IRender
    {
        public CanvasRender(Stage stage, SKCanvas canvas)
        {
            _instanceType = "annie.CanvasRender";
            this._stage = stage;
            this._canvas = canvas;
            //this._skPaint = new SKPaint();
        }

        public Sprite RootContainer { get; private set; } = null;

        //private SKPaint _skPaint = null;



        private Stage _stage = null;

        /// <summary>
        /// SkiaCanvas对象
        /// </summary>
        private SKCanvas _canvas = null;

        public void Begin()
        {
            _canvas.SetMatrix(new Matrix(1, 0, 0, 1, 0, 0).ToSkMatrix());

            if (_stage.BgColor != "")
            {
                throw (new Exception("未实现填充舞台背景色"));
            }
            else
            {
                _canvas.Clear();
            }
        }

        public void BeginMask(DisplayObject target)
        {
            throw new NotImplementedException();
        }



        public void Draw(DisplayObject target)
        {
            var stream = URLLoader.GetHttpClient().GetStreamAsync("http://annie2x.com/static/logo.jpg").Result;
            var task = Task.Run( () =>
            {
                //MemoryStream memStream = new MemoryStream();
                //stream.CopyToAsync(memStream).Wait();
                //memStream.Seek(0, SeekOrigin.Begin);
                return SKBitmap.Decode(stream);
            });
            //task.Wait();
            var texture = task.Result;
            if (texture!=null && texture.Width > 0 && texture.Height > 0)
            {
                using (var paint = new SKPaint())
                {
                    paint.Color = new SKColor(0, 0, 0, target.CAlpha.ToAlphaByte());

                    var tm = target.CMatrix;

                    _canvas.SetMatrix(tm.ToSkMatrix());

                    //遗漏IsCache属性
                    if (target.Rect != null)
                    {
                        _canvas.DrawBitmap(texture, target.Rect.ToSkRect(), paint);
                    }
                    else
                    {
                        _canvas.Translate(target.OffsetX, target.OffsetY);
                        _canvas.DrawBitmap(texture, 0, 0,paint);
                    }
                }
            }
        }

        public void EndMask()
        {
            _canvas.Restore();
        }

        public void Init()
        {
            //canvas对象暂时由外部传入，保持兼容保留此接口
        }

        public void ReSize()
        {
            throw new NotImplementedException();
        }

        public override void Destroy()
        {
            base.Destroy();
            //释放skia 画布，画笔
            _canvas.Dispose();
            //清除舞台的引用
            _stage = null;
        }
    }
}
